//
//  GasListVC.m
//  NtoccDriverNew
//
//  Created by niyongsheng on 2022/10/18.
//  Copyright © 2022 GCY. All rights reserved.
//

#import "GasListVC.h"
#import "GasListCell.h"
#import "GasListModel.h"
#import "GasMoneyVC.h"
#import "GasQrVC.h"

@interface GasListVC ()
<
UITableViewDelegate,
UITableViewDataSource
>
{
    NSInteger _pageNum;
    NSString *_keyword;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSourceMArr;
@end

@implementation GasListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    
    [self.tableView.mj_header beginRefreshing];
}

/// 刷新
/// @param isHeader 是否下拉刷新
- (void)refreshing:(BOOL)isHeader {
    if (isHeader) {
        _pageNum  = 1;
    } else {
        _pageNum ++;
    }

    NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],GasSpendList);
    NSMutableDictionary *params = @{
        @"pageNum" : @(_pageNum),
        @"pageSize" : @10,
        @"energyCardType" : self.typeStr
    }.mutableCopy;
    NSDictionary *branch = [UserDefaultUtil valueForKey:Login_Branch];
    [params setValue:branch[@"code"] forKey:@"driverCode"];
    [params setValue:_transactionStatus forKey:@"transactionStatus"];
    
    @weakify(self)
    [HTTPManager getNetworkRequest:urlStr
                     withParameter:params
                            withVC:self
                           netName:@"加油列表"
                           success:^(id response, NSString *msg) {
        @strongify(self)
        if (isHeader) {
            self.dataSourceMArr = [GasListModel mj_objectArrayWithKeyValuesArray:response[@"records"]];
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
            
        } else {
            NSArray *dictArr = response[@"records"];
            if (dictArr.count > 0) {
                [self.dataSourceMArr addObjectsFromArray:[GasListModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
                [self.tableView.mj_footer endRefreshing];
                [self.tableView reloadData];
                
            } else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    } failure:^(NSInteger code, NSString *msg) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - TableView 代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceMArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellReuseIdentifier = @"GasListCell";
    GasListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    GasListModel *model = self.dataSourceMArr[indexPath.row];
    cell.model = model;
    cell.block = ^(int index) {
        if (index == 1) {
            [self goonAddGas:model];
        } else {
            [self cancelAddGas:model];
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    GasMoneyVC *vc = [GasMoneyVC new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - MenuBarHeight - NavHeight) style:UITableViewStylePlain];
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([GasListCell class]) bundle:nil];
        [_tableView registerNib:nib forCellReuseIdentifier:NSStringFromClass([GasListCell class])];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        @weakify(self)
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self)
            [self refreshing:YES];
        }];
        header.lastUpdatedTimeLabel.hidden = YES;
        MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self refreshing:NO];
        }];
        
        _tableView.mj_header = header;
        _tableView.mj_footer = footer;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

/// 继续加油
/// - Parameter model: <#model description#>
- (void)goonAddGas:(GasListModel *)model {
    NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],GasDriverOilQrCodeNew);
    NSDictionary *params = @{
        @"serialNo": model.serialNo,
        @"energyCardType" : self.typeStr
    };
    @weakify(self)
    [HTTPManager getNetworkRequest:urlStr
                     withParameter:params
                            withVC:[UIViewController new]
                           netName:@"加油继续"
                           success:^(id response, NSString *msg) {
        @strongify(self)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_header beginRefreshing];
        });
        GasQrVC *vc = [GasQrVC new];
        vc.serialNo = model.serialNo;
        vc.qrUrl = response;
        [self.navigationController pushViewController:vc animated:YES];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

/// 取消加油
/// - Parameter model: <#model description#>
- (void)cancelAddGas:(GasListModel *)model {
    NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],GasStationPayment);
    NSDictionary *params = @{
        @"code": model.code,
        @"transactionStatus": @4,
        @"energyCardType" : self.typeStr
    };
    @weakify(self)
    [HTTPManager putNetworkRequest:urlStr
                     withParameter:params
                            withVC:[UIViewController new]
                           netName:@"加油取消"
                           success:^(id response, NSString *msg) {
        @strongify(self)
        [XSInfoView showInfo:@"已取消" onView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_header beginRefreshing];
        });
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

@end
